/* 
 * Enterprise Library Extensions - DI + ORM.
 * Copyright (C) 2006
 *
 * GNU General Public License
 *
 * This program is free software; you can redistribute 
 * it and/or modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation; either version 2 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * See the GNU General Public License for more details.
 */
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using ELE.EnterpriseLibrary.Data.Configuration;

namespace ELE.EnterpriseLibrary.Data
{
  /// <summary>
  /// Custom factory for a <see cref="ObjectSqlMappingManager"/>
  /// </summary>
  public class ObjectSqlMappingManagerCustomFactory : ICustomFactory
  {
    /// <summary>
    /// Creates an <see cref="ObjectSqlMappingManager"/> from a configuration source
    /// </summary>
    /// <param name="context"></param>
    /// <param name="name"></param>
    /// <param name="configurationSource"></param>
    /// <param name="reflectionCache"></param>
    /// <returns></returns>
    public object CreateObject(IBuilderContext context, string name, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
    {
      ObjectSqlMappingConfigurationView view = new ObjectSqlMappingConfigurationView(configurationSource);
      ObjectSqlMappingManager createdObject = new ObjectSqlMappingManager();
      MappingQueryData queryData = view.GetMappingQueryData(name);
      if (queryData != null)
      {
        foreach (ObjectMappingData oMap in queryData.Objects)
        {
          ObjectSqlMapping map = this.GetMappingQuery(view, queryData.Name, oMap.Name);
          if (map != null)
          {
            createdObject.AddMapping(oMap.Name, map);
          }
        }
        
      }

      RegisterObject(context, name, createdObject);
      return createdObject;
    }
    /// <summary>
    /// Get a mapping query
    /// </summary>
    /// <param name="view"></param>
    /// <param name="mappingName"></param>
    /// <param name="objectName"></param>
    /// <returns></returns>
    public ObjectSqlMapping GetMappingQuery(ObjectSqlMappingConfigurationView view, string mappingName, string objectName)
    {
      MappingQueryData mappingQuery = view.GetMappingQueryData(mappingName);

      QueryBuilderData qbData = view.GetQueryBuilderData(mappingQuery.QueryBuilder);
      ISqlQueryBuilder queryBuilder = (ISqlQueryBuilder) Activator.CreateInstance(Type.GetType(qbData.Type));

      return this.GetObjectSqlMapping(view, mappingQuery, queryBuilder, objectName);
    }

    private ObjectSqlMapping GetObjectSqlMapping(ObjectSqlMappingConfigurationView view, 
                                                 MappingQueryData mappingQuery, 
                                                 ISqlQueryBuilder queryBuilder,
                                                 string objectName)
    {
      ObjectSqlMapping mapping = null;
      if(mappingQuery.Objects.Contains(objectName))
      {
        mapping = new ObjectSqlMapping(objectName);
        mapping.QueryBuilder = queryBuilder;
        TypeData oType = view.GetObjectQueryData(objectName);
        mapping.ObjectType = oType.Type;
        AssemblyData assembly = view.GetAssemblyQueryData(oType.Assembly);
        mapping.ObjectAssembly = assembly.Value;

        ObjectMappingData objectMapping = mappingQuery.Objects.Get(objectName);
        int tableCount = 0;
        foreach (ObjectTableData tableData in objectMapping.Tables)
        {
          ObjectSqlMappingTable table = new ObjectSqlMappingTable(tableData.Name);
          if (tableData.Name == objectMapping.PrimaryTable || 
              (string.IsNullOrEmpty(objectMapping.PrimaryTable) && tableCount == 0))
          {
            table.IsPrimary = true;
            mapping.PrimaryTableName = tableData.Name;
          }
          else
          {
            table.JointColumn = tableData.JointColumn;
          }
          foreach (PropertyBindingData propertyBinding in tableData.Bindings)
          {
            ObjectPropertySqlBinding binding = new ObjectPropertySqlBinding(propertyBinding.Name);
            binding.PropertyName = propertyBinding.Property;
            binding.ColumnName = propertyBinding.ColumnName;
            binding.InputFieldName = propertyBinding.InName;
            binding.OutputFieldName = propertyBinding.OutName;
            binding.SqlType = propertyBinding.SqlType;
            binding.IsPrimaryKey = propertyBinding.PrimaryKey;
            binding.IsCollection = propertyBinding.IsCollection;
            binding.JointBinding = propertyBinding.JointBinding;
            binding.JointColumn = propertyBinding.JointColumn;
            binding.JointTable = propertyBinding.JointTable;
            binding.NullableValue = propertyBinding.NullableValue;
            binding.Ignore = propertyBinding.Ignore;
            if (!string.IsNullOrEmpty(propertyBinding.RefType))
            {
              if (!string.IsNullOrEmpty(binding.ColumnName) && string.IsNullOrEmpty(binding.JointColumn))
              {
                binding.JointColumn = binding.ColumnName;
              }
              binding.SubQuery = this.GetObjectSqlMapping(view, mappingQuery, queryBuilder, propertyBinding.RefType);
            }
            if (binding.IsPrimaryKey)
            {
              table.PrimaryKey = binding.Name;
            }
            table.AddBinding(binding);
          }
          mapping.AddTable(table);
        }
      }
      return mapping;
    }
    private void RegisterObject(IBuilderContext context, string name, ObjectSqlMappingManager createdObject)
    {
      if (context.Locator != null)
      {
        ILifetimeContainer lifetime = context.Locator.Get<ILifetimeContainer>(typeof(ILifetimeContainer), SearchMode.Local);

        if (lifetime != null)
        {
          context.Locator.Add(new DependencyResolutionLocatorKey(typeof(ObjectSqlMappingManager), name), createdObject);
          lifetime.Add(createdObject);
        }
      }
    }
  }

}
